var AppConfig = {
    setDifficultyLevel: function (difficultyLevel) {
        localStorage.setItem('difficultyLevel', difficultyLevel);
    },
    getDifficultyLevel: function () {
        if (localStorage.getItem('difficultyLevel') == null) {
            return 1;
        }
        return Number(localStorage.getItem('difficultyLevel'));
    },
    setDifficultyLabel: function (difficultyLabel) {
        localStorage.setItem('difficultyLabel', difficultyLabel);
    },
    getDifficultyLabel: function () {
        if (localStorage.getItem('difficultyLabel') == null) {
            return '简单';
        }
        return localStorage.getItem('difficultyLabel');
    },
    setBookContentId: function (bookContentId) {
        localStorage.setItem('bookContentId', bookContentId);
    },
    getBookContentId: function () {
        if (localStorage.getItem('bookContentId') == null) {
            return "110001";
        }
        return localStorage.getItem('bookContentId');
    },
    setBookContentLabel: function (bookContentLabel) {
        localStorage.setItem('bookContentLabel', bookContentLabel);
    },
    getBookContentLabel: function () {
        if (localStorage.getItem('bookContentLabel') == null) {
            return "国家 - 前10";
        }
        return localStorage.getItem('bookContentLabel');
    },
    // 获取一行中，空白单词长度
    getBlankWordLength: function (total) {
        if (AppConfig.getDifficultyLevel() == 1) {
            return Math.max(Math.floor(total / 3), 1);
        } else if (AppConfig.getDifficultyLevel() == 2) {
            return Math.floor(total / 2);
        } else {
            return Math.floor((2 * total) / 3);
        }
    },
    createBlockWordHtml: function (word) {
        return '<div class="block-word" data-value="' + word + '"><span>' + word + '</span></div>';
    },
    createBlockDroppableHtml: function (word) {
        return '<div class="block-droppable" data-value="' + word + '"><span></span></div>';
    },
    createBlockDraggableHtml: function (word) {
        return '<div class="block-draggable block-answer" data-value="' + word + '"><span>' + word + '</span></div>';
    },
    createImageHtml: function (img) {
        return '<div class="block-word" "><img src="image' + img + '.png" class="app-image"></div>';
    },
    setRandomSentenceNum: function (randomSentenceNum) {
        localStorage.setItem('randomSentenceNum', randomSentenceNum);
    },
    getRandomSentenceNum: function () {
        if (localStorage.getItem('randomSentenceNum') == null) {
            return 3;
        }
        return parseInt(localStorage.getItem('randomSentenceNum'));
    }
};

function refresh() {
    $('.container').remove();
    $('.container-answer').remove();
    renderHtml();
    renderResult($('#result'))
}

function renderResult($e) {
    $($e).text(AppConfig.getBookContentLabel() + " " + AppConfig.getDifficultyLabel());
}

function renderDrag($e) {
    $e.draggable({
        revert: 'invalid',
        helper: 'clone'
    });
    $e.draggable('enable');
    try {
        $e.droppable('disable');
    } catch (e) {

    }
}

function renderDrop($e) {
    try {
        $e.draggable('disable');
    } catch (e) {

    }
    $e.droppable({
        drop: drop
    });
    try {
        $e.droppable('enable');
    } catch (e) {

    }
}

/**
 * 拖动事件处理
 * 方格A->方格B
 * 1、始终使用方格A的内容填充方格B
 * 2、方格A是有当含有block-answer的样式（初始方格）才不用清空
 * @param event
 * @param ui
 */
function drop(event, ui) {
    const draggableText = $(ui.draggable).html();
    const droppableText = $(this).html();
    if ((droppableText != '<span></span>') && (draggableText != droppableText)) return;

    const draggableValue = $(ui.draggable).data('value');
    const droppableValue = $(this).data('value');
    const draggableSpan = '<span>' + draggableValue + '</span>';
    const droppableSpan = '<span>' + droppableValue + '</span>';

    // 1、始终使用方格A的内容填充方格B
    $(this).html(draggableText);

    $(ui.draggable).removeClass('block-draggable');
    $(ui.draggable).addClass('block-droppable');
    $(this).removeClass('block-droppable');
    $(this).addClass('block-draggable');

    renderDrag($(this));
    renderDrop($(ui.draggable));

    // 2、方格A是有当含有block-answer的样式（初始方格）才不用清空
    if (!$(ui.draggable).hasClass('block-answer')) {
        $(ui.draggable).html('<span></span>');
    }
}

function renderBookContent() {
    const bookContentId = AppConfig.getBookContentId();
    const bookContentArr = bookContentData[bookContentId];
    let matrix = new Array();
    for (let i = 0; i < bookContentArr.length; i++) {
        const bookContent = bookContentArr[i];
        matrix.push(bookContent);
    }
    return matrix;
}

function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function getRandomSplit(min, max, count) {
    // 生成包含1到10的数组
    const numbers = Array.from({length: max - min + 1}, (_, i) => i + min);

    // 洗牌
    const shuffledNumbers = shuffleArray(numbers);

    // 截取前count个元素
    const selectedNumbers = shuffledNumbers.slice(0, count);

    // 剩下的元素
    const remainingNumbers = shuffledNumbers.slice(count);

    return {selectedNumbers, remainingNumbers};
}

function randomSentence() {
    const matrix = renderBookContent();
    const randomSentenceNum = AppConfig.getRandomSentenceNum();
    const maxIndex = matrix.length - 1;
    var wordLength = maxIndex > randomSentenceNum ? randomSentenceNum : maxIndex;
    // 取随机行
    const {selectedNumbers, remainingNumbers} = getRandomSplit(0, maxIndex, wordLength);

    var sentenceArr = new Array();
    for (var i = 0; i < selectedNumbers.length; i++) {
        var j = selectedNumbers[i];
        sentenceArr.push(matrix[j]);
    }
    return sentenceArr;
}

/**
 * row是一句话，比如"我爱中国"，要转成"我”,”中”,”国”。"爱"保存到答案数组
 * 1、根据困难程度取n个字符，作为空白单词个数
 * 2、根据空白单词个数，随机取blankWords，remainingWords的字符下标数组
 * 3、row "我爱中国"转成["我”,"爱",”中”,”国”]wordArr
 * 4、根据blankWords字符下标，wordArr[blankWord]保存到answerArr，.container[blankWord]渲染成空<div>
 * 5、渲染answerArr，还要随机加字打乱
 */
function renderHtml() {
    const sentenceArr = randomSentence();
    // 答案数组
    let answerArr = new Array();
    sentenceArr.forEach(wordObj => {
        const row = Array.from(wordObj.name);
        const img = wordObj.img;
        // 1、根据困难程度取n个字符，作为空白单词个数
        const blankLength = AppConfig.getBlankWordLength(row.length);
        // 2、根据空白单词个数，随机取blankWords，remainingWords的字符下标数组
        const {selectedNumbers, remainingNumbers} = getRandomSplit(0, row.length - 1, blankLength);
        let blankWords = new Array();
        if (AppConfig.getDifficultyLevel() != 4) {
            // 如果不是全图模式，则只随机取空白字
            blankWords = selectedNumbers;
        } else {
            // 如果是全图模式，所有都是空白字
            blankWords = Array.from({length: row.length}, (_, index) => index);
        }
        // 3、row "我爱中国"转成["我”,"爱",”中”,”国”]wordArr
        const wordArr = Array.from(row).map(char => `${char}`);
        // 4、根据blankWords字符下标，wordArr[blankWord]保存到answerArr，.container[blankWord]渲染成空<div>
        const container = $('<div class="container"></div>');
        for (let i = 0; i < wordArr.length; i++) {
            if (blankWords.includes(i)) {
                // 渲染空白卡片
                container.append(AppConfig.createBlockDroppableHtml(wordArr[i]));
                answerArr.push(wordArr[i]);
            } else {
                // 渲染固定卡片
                container.append(AppConfig.createBlockWordHtml(wordArr[i]));
            }
        }
        container.append(AppConfig.createImageHtml(img));
        $('#tabbar-index').append(container);
    });
    // 5、渲染answerArr，还要随机加字打乱
    const {selectedNumbers, remainingNumbers} = getRandomSplit(0, mixArr.length - 1, 2);
    selectedNumbers.forEach(i => {
        const word = mixArr[i];
        answerArr.push(word);
    });
    answerArr = shuffleArray(answerArr);
    const container = $('<div class="container-answer"></div>');
    answerArr.forEach(word => {
        container.append(AppConfig.createBlockDraggableHtml(word));
        $('#tabbar-index').append(container);
    });

    renderDrag($('.block-draggable'));

    renderDrop($('.block-droppable'));
}
